package user

import (
	"context"
	"fmt"
	"strings"
	"time"

	"mall/common/cryptx"
	"mall/common/globalkey"
	"mall/common/modelx"
	"mall/common/resultx"
	"mall/service/user/model"
	"mall/service/user/rpc/internal/svc"
	"mall/service/user/rpc/types/user"

	"github.com/sirupsen/logrus"
	"github.com/volatiletech/null/v8"
	"github.com/zeromicro/go-zero/core/logx"
)

type LoginLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewLoginLogic(ctx context.Context, svcCtx *svc.ServiceContext) *LoginLogic {
	return &LoginLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *LoginLogic) Login(in *user.LoginReq) (*user.BaseIDResp, error) {
	if in.AuthType == nil || len(strings.TrimSpace(*in.AuthType)) == 0 {
		return nil, resultx.StatusError(resultx.USER_AUTH_PARAM_INVALID, "")
	}

	if in.AuthKey == nil || len(strings.TrimSpace(*in.AuthKey)) == 0 {
		return nil, resultx.StatusError(resultx.USER_AUTH_PARAM_INVALID, "")
	}

	if in.Password == nil || len(strings.TrimSpace(*in.Password)) == 0 {
		return nil, resultx.StatusError(resultx.USER_AUTH_PARAM_INVALID, "")
	}

	var userId uint64
	var err error
	switch strings.TrimSpace(*in.AuthType) {
	case globalkey.UserAuthTypeMobile, globalkey.UserAuthTypeEmail, globalkey.UserAuthTypeUsername:
		userId, err = l.systemLogin(in)
	default:
		return nil, resultx.StatusError(resultx.USER_AUTH_PARAM_INVALID, "")
	}
	if err != nil {
		return nil, err
	}
	//登录成功后 添加最近一次登录时间
	err = l.svcCtx.CurrentUser.UpdateMetum(l.ctx, nil, &model.UserMetum{
		UserID:    userId,
		MetaKey:   "_last_login_time",
		MetaValue: null.StringFrom(modelx.FormatTime(time.Now(), "")),
	})
	if err != nil {
		logrus.Info(fmt.Sprintf("LastLoginTime  err: %+v", err))
		return nil, err
	}
	return &user.BaseIDResp{
		Id: userId,
	}, nil
}

func (l *LoginLogic) systemLogin(in *user.LoginReq) (userId uint64, err error) {
	authType := strings.TrimSpace(*in.AuthType)
	authKey := strings.TrimSpace(*in.AuthKey)
	pwd := strings.TrimSpace(*in.Password)

	// 查询用户是否存在
	filterMap := make(map[string]map[string][]any)
	switch authType {
	case globalkey.UserAuthTypeMobile:
		filterMap[model.UserColumns.UserMobile] = map[string][]any{
			"equalTo": []any{authKey},
		}
	case globalkey.UserAuthTypeEmail:
		filterMap[model.UserColumns.UserEmail] = map[string][]any{
			"equalTo": []any{authKey},
		}
	case globalkey.UserAuthTypeUsername:
		filterMap[model.UserColumns.UserLogin] = map[string][]any{
			"equalTo": []any{authKey},
		}
	}
	selectCols := []string{
		model.UserColumns.ID,
		model.UserColumns.UserPass,
		model.UserColumns.Salt,
		model.UserColumns.UserStatus,
	}
	userList, _, err := l.svcCtx.CurrentUser.GetList(l.ctx, model.M{
		"pageSize": uint64(1),
		"select":   strings.Join(selectCols, ","),
	}, -1, filterMap)
	if err != nil {
		return 0, err
	}
	if len(userList) == 0 {
		return 0, resultx.StatusError(resultx.USER_AUTH_PARAM_INVALID, "")
	}

	user := userList[0]
	// 判断用户状态
	if user.UserStatus != uint16(globalkey.StatusEnabled) {
		return 0, resultx.StatusError(resultx.USER_STATUS_INVALID, "")
	}

	// 判断密码是否正确
	passwordEncrypt := cryptx.PasswordEncrypt(user.Salt, pwd)
	if passwordEncrypt != user.UserPass {
		return 0, resultx.StatusError(resultx.USER_AUTH_PARAM_INVALID, "")
	}

	return user.ID, nil
}
